20230502 estsoft - python - str, cpython, indexing and slicing, numeric operations, bit operations, is, not, in

str

# 퀴즈
# 숫자만 모두 더하라!
num = "123abc913sldkf"
result = sum(map(int, filter(lambda x: x.isnumeric(), num)))
print(result)

indexing and slicing

슬라이스 결과는 slice 객체이다. 내부적으로 slice() 내장함수를 호출한다.

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

a[start:stop:step] # start through not past stop, by step

# start and stop may be a negative number
a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

# steps can be a negative number
a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

numeric operation

a = 10
b = 3

print(f'10 + 3 == {a + b}')
print(f'10 - 3 == {a - b}')
print(f'10 / 3 == {a / b}')
print(f'10 // 3 == {a // b}') # 몫만 나옵니다.(정수만요!)
print(f'10 * 3 == {a * b}')
print(f'10 ** 3 == {a ** b}')
print(f'10 % 3 == {a % b}') # 나머지

is, not

is== 과 다르게 객체의 id를 보고 비교한다. 그래서 다음과 같은 이상한 현상을 발견할 수 있다.

a = 256
b = 256
assert a is b

-5부터 256까지는 기본 공간에 저장되어있는 수를 가리킨다고 했지?

a = 9999
b = 9999
assert a is not b

리스트는 언제나 항상 다르다.

a = [1, 2, 3]
b = [1, 2, 3]
assert a == b
assert a is not b

member operator in

assert not 'a' in 'hello, world'
assert 'a' in ['a', 'b']
assert 10 in {'a':10, 'b':20}.values()